package com.jming.jike.util;


import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 复制对象工具
 *
 * @author cbest
 */
public class CopyBeanUtils {

    /**
     * 复制对象
     *
     * @param sourceObj 源对象
     * @param targetObj 目标对象
     * @return 返回复制后的目标对象
     */
    public static <T> T copyBean(Object sourceObj, T targetObj) {

        if (sourceObj == null) {
            return targetObj;
        }

        BeanUtils.copyProperties(sourceObj, targetObj);
        return targetObj;
    }


    /**
     * 复制列表
     *
     * @param sourceList  源列表数据
     * @param targetClass 目标的类信息
     * @return 返回复制后的结果
     */
    public static <T> List<T> copyBeanList(List<?> sourceList, Class<T> targetClass) {

        try {
            List<T> targetList = new ArrayList<>();
            if (sourceList == null) {
                return targetList;
            }
            for (Object obj : sourceList) {
                targetList.add(copyBean(obj, targetClass.newInstance()));
            }

            return targetList;
        } catch (Exception e) {
            throw new RuntimeException("列表复制失败!");
        }
    }
}
